package metro.cards;

import metro.cards.types.CardType;
import metro.response.Response;
import metro.system.MetroSystem;
import metro.tourniquet.Tourniquet;

import java.util.Calendar;

public class DurationCard extends Card {
    protected Calendar expiredDate;
    protected Calendar startDate;

    protected DurationCard(Calendar creationDate,Calendar startDate,Calendar expiredDate) {
        this(creationDate);
        this.expiredDate = expiredDate;
        this.startDate=startDate;
    }

    protected DurationCard(Calendar creationDate,Calendar expiredDate) {
        this(creationDate,creationDate,expiredDate);
    }

    private DurationCard(Calendar creationDate){
        super(creationDate);
        type= CardType.DURATION_CARD;
    }

    public static DurationCard createMonthCard(Calendar creationDate){
        Calendar current=(Calendar)creationDate.clone();
        current.add(Calendar.MONTH,1);
        current.add(Calendar.DAY_OF_YEAR,1);
        return new DurationCard(creationDate,current);
    }

    public static DurationCard createNextMonthCard(Calendar creationDate){
        return new DurationCard(creationDate,nextMonthFirstDay(), nextMonthLastDay());
    }

    public static Calendar nextMonthFirstDay() {
        Calendar startDate=Calendar.getInstance();
        startDate.add(Calendar.MONTH, 1);
        startDate.set(Calendar.DAY_OF_MONTH, 1);
        startDate.set(Calendar.HOUR_OF_DAY, 0);
        startDate.set(Calendar.MINUTE, 0);
        startDate.set(Calendar.SECOND, 0);
        return startDate;
    }

    public static Calendar nextMonthLastDay(){
        Calendar expiredDate=Calendar.getInstance();
        expiredDate.add(Calendar.MONTH, 2);
        expiredDate.set(Calendar.DAY_OF_MONTH, 1);
        expiredDate.add(Calendar.DAY_OF_YEAR,-1);
        expiredDate.set(Calendar.HOUR_OF_DAY, 23);
        expiredDate.set(Calendar.MINUTE, 59);
        expiredDate.set(Calendar.SECOND, 59);
        return expiredDate;
    }

    public Calendar getExpiredDate() {
        return expiredDate;
    }

    public Calendar getStartDate() {
        return startDate;
    }

    @Override
    public Response use(MetroSystem system,Tourniquet tourniquet) {
        //Was Calendar.getInstance()
        //Don't know is it correct. Add /system.getCurrentDate()/ just for easier testing
        Calendar currentDate=system.getCurrentDate();
        if (currentDate.before(expiredDate) && currentDate.after(startDate))
            return Response.createPositiveDurationResponse(currentDate, this,tourniquet);
        else return Response.createNegativeTimeResponse(this,tourniquet);
    }

    public static int dateDiffInDays (Calendar current,Calendar next){
        return (int)(next.getTimeInMillis()-current.getTimeInMillis())/(1000*60*60*24);
    }
}
